<template>
  <div class="oss-image-manager">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>阿里云OSS图片管理</span>
          <el-button type="primary" @click="fetchImages">刷新</el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入文件名进行搜索"
          clearable
          style="width: 300px; margin-right: 12px;"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <!-- 添加模块搜索下拉框 -->
        <el-select
          v-model="searchModule"
          placeholder="请选择模块"
          clearable
          style="width: 150px; margin-right: 12px;"
          @change="handleSearch"
        >
          <el-option label="我的笔记" value="我的笔记" />
          <el-option label="常识积累" value="常识积累" />
          <el-option label="时政积累" value="时政积累" />
          <el-option label="作文素材" value="作文素材" />
          <el-option label="词语积累" value="词语积累" />
          <el-option label="成就管理" value="成就管理" />
          <el-option label="时政题目" value="时政题目" />
          <el-option label="常识题目" value="常识题目" />
          <el-option label="言语理解题目" value="言语理解题目" />
          <el-option label="数量题目" value="数量题目" />
          <el-option label="判断题目" value="判断题目" />
          <el-option label="资料分析题目" value="资料分析题目" />
          <el-option label="错题题目" value="错题题目" />
          <el-option label="申论题目" value="申论题目" />
          <el-option label="AI聊天" value="AI聊天" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="clearSearch">清空</el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedImages.length === 0" style="margin-left: 12px;">
          批量删除 ({{ selectedImages.length }})
        </el-button>
      </div>
      
      <!-- 上传区域 -->
      <div class="upload-section">
        <!-- 添加模块选择 -->
        <div class="module-select">
          <el-select
            v-model="uploadModule"
            placeholder="请选择上传模块（可选）"
            clearable
            style="width: 200px; margin-bottom: 15px;"
          >
            <el-option label="我的笔记" value="我的笔记" />
            <el-option label="常识积累" value="常识积累" />
            <el-option label="时政积累" value="时政积累" />
            <el-option label="作文素材" value="作文素材" />
            <el-option label="词语积累" value="词语积累" />
            <el-option label="成就管理" value="成就管理" />
            <el-option label="时政题目" value="时政题目" />
            <el-option label="常识题目" value="常识题目" />
            <el-option label="言语理解题目" value="言语理解题目" />
            <el-option label="数量题目" value="数量题目" />
            <el-option label="判断题目" value="判断题目" />
            <el-option label="资料分析题目" value="资料分析题目" />
            <el-option label="错题题目" value="错题题目" />
            <el-option label="申论题目" value="申论题目" />
            <el-option label="AI聊天" value="AI聊天" />
          </el-select>
        </div>
        <el-upload
          class="upload-demo"
          drag
          :action="uploadUrl"
          :headers="uploadHeaders"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
          multiple>
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              jpg/png/gif/bmp 文件大小不超过 10MB
            </div>
          </template>
        </el-upload>
      </div>
      
      <!-- 图片列表 -->
      <div class="image-list">
        <el-table 
          :data="filteredImageList" 
          style="width: 100%" 
          v-loading="loading"
          element-loading-text="加载中..."
          class="image-table"
          @selection-change="handleSelectionChange"
          height="600">
          <el-table-column type="selection" width="55" />
          <el-table-column label="预览" width="150" align="center">
            <template #default="scope">
              <el-image
                :src="scope.row.accessUrl"
                :preview-src-list="[scope.row.accessUrl]"
                :initial-index="0"
                fit="cover"
                style="width: 100px; height: 100px; border-radius: 8px;"
                lazy
                :preview-teleported="true">
                <template #error>
                  <div class="image-slot">
                    <el-icon><icon-picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="fileName" label="文件名" min-width="250">
            <template #default="scope">
              <span class="filename">{{ scope.row.fileName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="fileSize" label="文件大小" width="120" align="center">
            <template #default="scope">
              <span>{{ formatFileSize(scope.row.fileSize) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="module" label="所属模块" width="120" align="center">
            <template #default="scope">
              <span>{{ scope.row.module || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="上传时间" width="200" align="center">
            <template #default="scope">
              <span>{{ formatTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center" fixed="right">
            <template #default="scope">
              <div class="action-buttons">
                <el-button 
                  size="small" 
                  type="primary" 
                  @click="copyImageUrl(scope.row.accessUrl)"
                  class="action-button">
                  复制链接
                </el-button>
                <el-button 
                  size="small" 
                  type="danger" 
                  @click="deleteImage(scope.row.fileId)"
                  class="action-button">
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled, Picture as IconPicture, Search } from '@element-plus/icons-vue'
import { getUserFiles, deleteFile, batchDeleteFiles } from '@/api/upload'
import { useUserStore } from '@/stores/user'

// 状态管理
const imageList = ref<any[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('') // 搜索关键词
const searchModule = ref('') // 模块搜索关键词
const uploadModule = ref('') // 上传模块
const selectedImages = ref<any[]>([]) // 选中的图片

// 用户存储
const userStore = useUserStore()

// 上传相关
const uploadUrl = computed(() => {
  if (uploadModule.value) {
    return `/api/upload/file?module=${encodeURIComponent(uploadModule.value)}`
  }
  return '/api/upload/file'
})
const uploadHeaders = computed(() => {
  return {
    'Authorization': `Bearer ${userStore.token}`
  }
})

// 计算过滤后的图片列表
const filteredImageList = computed(() => {
  let filtered = imageList.value
  
  // 如果有搜索关键词，进行过滤
  if (searchKeyword.value.trim()) {
    filtered = imageList.value.filter(item => 
      item.fileName && item.fileName.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
  }
  
  // 如果有模块搜索关键词，进行过滤
  if (searchModule.value) {
    filtered = filtered.filter(item => 
      item.module && item.module === searchModule.value
    )
  }
  
  // 更新总数
  total.value = filtered.length
  
  // 实现分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(2) + ' MB'
  }
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  return true
}

// 上传成功处理
const handleUploadSuccess = (response: any, file: any, fileList: any[]) => {
  if (response.code === 200) {
    ElMessage.success('上传成功')
    // 上传成功后清空模块选择
    uploadModule.value = ''
    fetchImages()
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

// 上传失败处理
const handleUploadError = (error: any, file: any, fileList: any[]) => {
  ElMessage.error('上传失败: ' + (error.message || '未知错误'))
}

// 获取图片列表
const fetchImages = async () => {
  loading.value = true
  try {
    // 如果有模块搜索条件，传递模块参数
    const params: any = {}
    if (searchModule.value) {
      params.module = searchModule.value
    }
    
    const response: any = await getUserFiles(params)
    if (response.code === 200) {
      imageList.value = response.data || []
      total.value = imageList.value.length
    } else {
      ElMessage.error(response.message || '获取图片列表失败')
    }
  } catch (error) {
    ElMessage.error('获取图片列表失败: ' + (error as Error).message)
  } finally {
    loading.value = false
  }
}

// 删除图片
const deleteImage = async (fileId: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response: any = await deleteFile(fileId)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchImages()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error as Error).message)
    }
  }
}

// 复制图片链接
const copyImageUrl = (url: string) => {
  navigator.clipboard.writeText(url).then(() => {
    ElMessage.success('链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

// 分页相关
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1 // 搜索时重置到第一页
}

// 清空搜索
const clearSearch = () => {
  searchKeyword.value = ''
  searchModule.value = ''
  currentPage.value = 1
}

// 处理选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedImages.value = selection
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedImages.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedImages.value.length} 张图片吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const fileIds = selectedImages.value.map(item => item.fileId)
    const response: any = await batchDeleteFiles(fileIds)
    
    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      selectedImages.value = [] // 清空选择
      fetchImages()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败: ' + (error as Error).message)
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchImages()
})
</script>

<style scoped>
.oss-image-manager {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-section {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 12px;
}

.upload-section {
  margin-bottom: 30px;
}

.image-list {
  margin-bottom: 20px;
}

.image-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.filename {
  font-size: 14px;
  color: #606266;
  word-break: break-all;
  padding: 0 10px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-button {
  padding: 8px 12px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  border-radius: 8px;
}

.image-slot .el-icon {
  font-size: 30px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-section :deep(.el-input) {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 12px;
  }
  
  .image-table :deep(.el-table__cell) {
    padding: 8px 0;
  }
  
  .filename {
    font-size: 12px;
    padding: 0 5px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
  
  .action-button {
    padding: 6px 10px;
    font-size: 12px;
  }
}
</style>